﻿// =================================================================== 
// 项目说明
//====================================================================
// sushee @Copy Right 2019
// 文件： SmsTaskTimeRepository.cs
// 项目名称：斑马车务
// 创建时间：2019/9/19
// 负责人：sushee
// ===================================================================
using System;
using System.Text;
using System.Collections.Generic;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Models;
using Dapper.Extensions;
using Dapper;

namespace YouWei.Infrastructure.Repository
{
	/// <summary>
	///短信任务执行周期 仓储层
	/// </summary>	
	public class SmsTaskTimeRepository:BaseRepository<SmsTaskTime>
	{		
    
        #region 构造

        public SmsTaskTimeRepository() : base(){}

        public SmsTaskTimeRepository(string connectionString) : base(connectionString){}

        public SmsTaskTimeRepository(DatabaseContext dbContext) : base(dbContext){}

        #endregion

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public Page<SmsTaskTimeDto> GetPages(int pageIndex, long pageSize,int taskId)
        {
            string sql = "SELECT * FROM SmsTaskTime WITH(NOLOCK) where TaskID=@TaskID";
            DynamicParameters dparams = new DynamicParameters();
            dparams.Add("@TaskID", taskId, System.Data.DbType.Int32);
            return dbContext.Connection.Page<SmsTaskTimeDto>(pageIndex, pageSize, sql, dparams);
        }


	    public List<SmsTaskTime> GetCardStatusReport(int cardID,DateTime dtTime)
	    {
            string szSql = @"SELECT 
	                        stt.*
                        FROM SmsTaskTime stt
                        INNER JOIN SmsTask t
                        ON t.TaskID=stt.TaskID
                        INNER JOIN SmsTaskCard stc
                        ON stc.TaskID=t.TaskID and stc.CardID=@CardID
                        WHERE 
                        1=1
                        AND  @dtTime>t.StartDate and @dtTime<t.EndDate and t.IsDeleted=0 and t.Status=1
                        AND  datepart(hh,@dtTime)>=stt.StartTime and datepart(hh,@dtTime)<stt.EndTime";
            
            return Query(szSql,new { CardID = cardID, dtTime = dtTime });
        }

        public int GetTaskCardCount(int taskID,DateTime dtTime)
        {
            string szSql = @"		select 
							COUNT(distinct CardID)
					    from
						SmsTaskTime stt
                        INNER JOIN SmsTask t
                        ON t.TaskID=stt.TaskID
						INNER JOIN SmsTaskCard  stc
						ON stt.TaskID=stc.TaskID
						Where 
					    @dtTime>t.StartDate and @dtTime<t.EndDate and t.IsDeleted=0 and t.Status=1
						AND stc.TaskID=@TaskID";

            return Database.Connection.ExecuteScalar<int>(szSql, new { TaskID=taskID, dtTime = dtTime });
        }
    }
}